package com.zf.nospring.rocketmq.sql_filter;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 过滤消息，使用 SQL 样式的语法，来过滤消息，只消费满足条件的数据
 */
public class FilterConsumerTest {
    public static void main(String[] args) throws MQClientException {
        // 创建消息消费者, 指定消费者所属的组名。使用 Push模式，是对 Pull 模式的包装
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("no-spring-cg");
        // 指定Nameserver地址
        consumer.setNamesrvAddr("localhost:9876");

        // 指定消费者订阅的主题
        // 使用属性过滤消息
        consumer.subscribe("test_topic", MessageSelector.bySql("a between 3 and 5"));
        // 使用回调函数处理推送的消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
                for (MessageExt message : messages) {
                    System.out.printf("body：%s\n", new String(message.getBody()));
                }
                //返回消费状态，表示消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 启动消息消费者
        consumer.start();
    }
}
